using System;
using UnityEngine;
using QFramework;

namespace ProjectMyFarmAndShe
{
	public partial class EmailPanel : ViewController,IController
	{
		private IEmailSystem mSystem;
		
		private void Awake()
		{
			EmailItemTemplate.Hide();

			mSystem = this.GetSystem<IEmailSystem>();
		}

		void Start()
		{
			// Code Here
            CloseBtn.onClick.AddListener(() =>
            {
	            this.Hide();
	            Global.OpenPanel.Value = false;
            });
            
            UpdateEmail();

            EmailSystem.OnAddEmail.Register(() =>
	            {
		            UpdateEmail();
		            MessagePanel.Default.AddMessage("有最新来信");
	            })
	            .UnRegisterWhenGameObjectDestroyed(gameObject);

            this.Hide();
		}

		void UpdateEmail()
		{
			Content.DestroyChildren();
			
			foreach (var data in mSystem.EmailDatas)
			{
				EmailItemTemplate.InstantiateWithParent(Content)
					.Self(self =>
					{
						self.Init(data);
						self.SetPointerClickAction((emailData) =>
						{
							EmailDetailPanel.Show();
							EmailDetailPanel.UpdateDetail(emailData);
							if (emailData.IsRead.Value) return;
							emailData.IsRead.Value = true;
						});
					})
					.Show();
			}
		}

		private void OnDisable()
		{
			EmailDetailPanel.Hide();
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}
